var backServerUrl = "https://wysiwyg.work:9999"; //正式
// var backServerUrl = "http://127.0.0.1:9999/";
// var backServerUrl = "https://wysiwyg.work:9998"; //体验

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

function clearHeartBeatInterval() {
  var globalData = getApp().globalData;
  if (globalData.interval) {
    try {
      clearInterval(globalData.interval)
      globalData.interval = "";
    } catch (e) {
      console.log(e)
    }
  }
}

function loginTimeOut() {
  clearHeartBeatInterval();
  wx.showLoading({
    title: '登录超时...',
  })
  wx.clearStorageSync();
  wx.setStorageSync('autoLogin', "1");
  setTimeout(
    () => {
      wx.hideLoading();
      wx.redirectTo({
        url: '/pages/login/login'
      })
    },
    2 * 1000);
}

function postRequest(url, data, sucessCallback, errorCallback) {
  var accessToken = wx.getStorageSync('accessToken');
  if (accessToken) {
    accessToken = accessToken + "-" + wx.getStorageSync('userInfo').id;
  }
  wx.request({
    url: backServerUrl + url,
    method: "POST",
    data: {
      data: data
    },
    header: {
      'X-APPLET-TOKEN': accessToken,
      'content-type': 'application/json' // 默认值
    },
    success: (res) => {
      //跳转登录页
      if (res.statusCode == 401) {
        loginTimeOut();
        return;
      }
      var data = res.data;
      //刷新token出现异常
      if (data && data.code == 401) {
        loginTimeOut();
        return;
      }
      if (sucessCallback) {
        sucessCallback(data)
      }
    },
    fail: (error) => {
      console.log(error)
      if (errorCallback) {
        errorCallback(error)
      }
    }
  })
}

function uploadFile(url, tempFilePath, data, sucessCallback, errorCallback) {
  var accessToken = wx.getStorageSync('accessToken');
  if (accessToken) {
    accessToken = accessToken + "-" + wx.getStorageSync('userInfo').id;
  }
  wx.uploadFile({
    url: backServerUrl + url, //仅为示例，非真实的接口地址
    filePath: tempFilePath,
    header: {
      'X-APPLET-TOKEN': accessToken
    },
    name: 'file',
    formData: data,
    success: (res) => {
      if (res.statusCode == 401) {
        loginTimeOut();
        return;
      }
      var data = res.data;
      if (sucessCallback) {
        sucessCallback(data)
      }
    },
    fail: (error) => {
      if (errorCallback) {
        errorCallback(error)
      }
    }
  })
}

function downloadFile(url, sucessCallback, errorCallback) {
  wx.downloadFile({
    url: url,
    success: (res) => {
      if (res.statusCode == 401) {
        loginTimeOut();
        return;
      }
      if (sucessCallback) {
        sucessCallback(res)
      }
    },
    fail: (error) => {
      if (errorCallback) {
        errorCallback(error)
      }
    }
  })
}


function isBlank(str) {
  if (str.length == 0 || /\s/.test(str) || str.includes(" "))
    return true;
  return false
}

var defaultAvatarUrl = "../../images/my_1.png";
var defaultUsername = "车上说";
var defaultServerAvatarUrl = "/images/default/my_1.png";


function getRandomCode(length) {
  if (length > 0) {
    var data = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
    var nums = "";
    for (var i = 0; i < length; i++) {
      var r = parseInt(Math.random() * 61);
      nums += data[r];
    }
    return nums;
  } else {
    return false;
  }
}

module.exports = {
  formatTime,
  postRequest,
  isBlank,
  uploadFile,
  downloadFile,
  defaultAvatarUrl,
  defaultServerAvatarUrl,
  getRandomCode,
  backServerUrl,
  defaultUsername,
  loginTimeOut,
  clearHeartBeatInterval
}